﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.HealthCheckPackageCommand;
using D.Medicalcare.Write.API.Application.Commands.IntroductionHospital;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.HealthCheckPackageHandler
{
    /// <summary>
    /// 新增体验套餐命令处理器
    /// </summary>
    public class AddHealthCheckPackageHandler : IRequestHandler<AddHealthCheckPackageCommand, APIResult<int>>
    {

        private readonly IMapper mapper;
        private readonly IBaseRepository<HealthCheckPackage> baseRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper">映射</param>
        /// <param name="baseRepository">仓储</param>
        public AddHealthCheckPackageHandler(IMapper mapper, IBaseRepository<HealthCheckPackage> baseRepository)
        {
            this.mapper = mapper;
            this.baseRepository = baseRepository;
        }

        /// <summary>
        /// 处理请求
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">参数</param>
        /// <returns></returns>
        public async Task<APIResult<int>> Handle(AddHealthCheckPackageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var model = mapper.Map<HealthCheckPackage>(request);
                model.PackageNo = GenerateProjectNumber();
                model.IsDeleted = false;
                var dto = baseRepository.AddAsync(model).Result;
                if (dto > 0)
                {
                    result.Code = APIEnum.Success;
                    result.Msg = "添加成功";
                    result.Data = dto;
                }
                else
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "添加失败";
                    return await Task.FromResult(result);
                }

                return await Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 生成项目编号
        /// </summary>
        /// <returns></returns>
        public static string GenerateProjectNumber()
        {
            // 这里可以根据具体需求修改编号生成规则
            // 例如：当前日期 + 随机数
            string datePart = DateTime.Now.ToString("yyyyMMdd");
            string randomPart = new Random().Next(1000, 9999).ToString();
            return $"XMBH{datePart}{randomPart}";
        }
    }
}
